package com.example.demo.data.user;

import com.example.demo.webconfig.securityconfig.authenticationconfig.UserGrantedAuthority;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.security.Key;
import java.util.*;

public class UserBo extends User implements UserDetails
{
    private String password;
    private Logger logger = LoggerFactory.getLogger(UserBo.class);
    private static final Map<Long, Key> loginUserIdSet = new HashMap<>();
    public UserBo(UserDo userDo)
    {
        super();
        this.password = userDo.getPassword();
        setAuth(userDo.getAuth());
        setDept_id(userDo.getDept_id());
        setDept_name(userDo.getDept_name());
        setId(userDo.getId());
        setName(userDo.getName());
        setType(userDo.getType());
    }

    public void setPassword(String password)
    {
        if (password.matches("^([0-9]|[a-z]|[A-Z]){6,30}$"))
        {
            this.password = password;
        }
        else
        {
            logger.warn("Invalid user password");
            throw new IllegalArgumentException("Invalid user password");
        }
    }

    public static synchronized void loginUser(long userId, Key tokenKey)
    {
        loginUserIdSet.put(userId, tokenKey);
    }

    public static boolean isLoggedin(long userId)
    {
        return loginUserIdSet.containsKey(userId);
    }

    public static synchronized void logoutUser(long userId)
    {
        loginUserIdSet.remove(userId);
    }

    public static Key getUserTokenKey(long userId)
    {
        return loginUserIdSet.get(userId);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities()
    {
        List<UserGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new UserGrantedAuthority(getAuth()));
        authorities.add(new UserGrantedAuthority(getType()));
        return authorities;
    }

    @Override
    public String getPassword()
    {
        return this.password;
    }

    @Override
    public String getUsername()
    {
        return this.getName();
    }

    @Override
    public boolean isAccountNonExpired()
    {
        return true;
    }

    @Override
    public boolean isAccountNonLocked()
    {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired()
    {
        return true;
    }

    @Override
    public boolean isEnabled()
    {
        return true;
    }

}
